//
//  FavAlbum.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/19.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation
import CoreData

private let entityName = CoreDataEntityName.favAlbum.rawValue
private let context = CoreDataHelper.getContext()

extension FavAlbum {
  static func getAll() -> [FavAlbum]? {
    let request = NSFetchRequest<FavAlbum>()
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
    request.entity = entity
    request.predicate = NSPredicate(format: "userID = %@", "\(UserManager.shared.currentUser!.identifier)")
    request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
    do {
      let favAlbums = try context.fetch(request)
      return favAlbums
    } catch let error {
      loggingPrint(error)
      return nil
    }
  }
  
  static func add(albumID: Int) -> FavAlbum? {
    do {
      if try FavAlbum.get(albumID: albumID) == nil {
        let favAlbum = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! FavAlbum
        favAlbum.id = NSUUID().uuidString
        favAlbum.albumID = Int16(albumID)
        favAlbum.createdAt = Date()
        if let currentUser = UserManager.shared.currentUser {
          favAlbum.userID = Int16(currentUser.identifier)
        }
        
        do {
          try context.save()
          return favAlbum
        } catch let error {
          loggingPrint(error)
          return nil
        }
      } else {
        return nil
      }
    } catch let error {
      loggingPrint(error)
      return nil
    }
  }
  
  static func remove(_ favAlbum: FavAlbum) throws {
    context.delete(favAlbum)
    do {
      try context.save()
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
  
  static func remove(id: Int) throws {
    if let favAlbum = EntityManager.fetch(FavAlbum.self, fetchType: .id(id))?.first {
      context.delete(favAlbum)
      do {
        try context.save()
      } catch let error {
        loggingPrint(error)
        throw error
      }
    }
  }
  
  static func get(albumID: Int) throws -> FavAlbum? {
    let request = NSFetchRequest<FavAlbum>()
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
    request.entity = entity
    request.predicate = NSPredicate(format: "userID = %@ && albumID = %@", "\(UserManager.shared.currentUser!.identifier)", "\(albumID)")
    do {
      let favAlbum = try context.fetch(request).first
      return favAlbum
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
}
